package com.concurrent.sample.business.config;

import com.concurrent.sample.business.consts.BusinessConsts;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class BusinessThreadPoolConfig {

  /**
   * 确认交易线程池
   * @return
   */
  @Bean(name = BusinessConsts.ASYNC_EXAMINE_TRADE_EXECUTOR)
  public Executor confirmTradeExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    initCommonParams(taskExecutor);
    taskExecutor.setCorePoolSize(8);
    taskExecutor.setMaxPoolSize(8);
    taskExecutor.setQueueCapacity(Integer.MAX_VALUE);
    taskExecutor.setThreadNamePrefix(BusinessConsts.ASYNC_EXAMINE_TRADE_EXECUTOR + "-");
    taskExecutor.initialize();
    return taskExecutor;
  }

  /**
   * 交易成交回报线程池
   * @return
   */
  @Bean(name = BusinessConsts.ASYNC_TRADE_EXEC_REPORT_EXECUTOR)
  public Executor tradeExecReportExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    initCommonParams(taskExecutor);
    taskExecutor.setCorePoolSize(8);
    taskExecutor.setMaxPoolSize(8);
    taskExecutor.setQueueCapacity(Integer.MAX_VALUE);
    taskExecutor.setThreadNamePrefix(BusinessConsts.ASYNC_TRADE_EXEC_REPORT_EXECUTOR + "-");
    taskExecutor.initialize();
    return taskExecutor;
  }

  private void initCommonParams(ThreadPoolTaskExecutor taskExecutor) {
    taskExecutor.setKeepAliveSeconds(60);
    taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
    taskExecutor.setAwaitTerminationSeconds(60);
    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  }

}
